package com.comtop.topcloud.device.service.impl;

import com.alibaba.fastjson.JSON;
import com.comtop.topcloud.device.model.mysql.OperationProjectInfo;
import com.comtop.topcloud.device.mapper.OperationProjectInfoMapper;
import com.comtop.topcloud.device.service.OperationProjectInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.comtop.topcloud.device.service.redis.RedisCacheService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 项目信息 服务实现类
 * </p>
 *
 * @author 张俊彬
 * @since 2025-01-04
 */
@Service
public class OperationProjectInfoServiceImpl extends ServiceImpl<OperationProjectInfoMapper, OperationProjectInfo> implements OperationProjectInfoService {
    @Autowired
    private RedisCacheService redisCacheService;

    private static final String CACHE_PREFIX = "operation_project_info:";  // 缓存的 key 前缀

    /**
     * 根据项目ID查询项目数据，首先查询缓存，如果缓存中没有则从数据库查询并存入缓存
     */
    public OperationProjectInfo getById(String projectId) {
        // 从 Redis 中获取数据
        String cacheKey = CACHE_PREFIX + projectId;
        String cachedData = redisCacheService.getCache(cacheKey);

        // 如果缓存中存在数据，则直接返回
        if (!StringUtils.isEmpty(cachedData)) {
            if ("null".equals(cachedData)) {
                return null;
            }
            return JSON.parseObject(cachedData, OperationProjectInfo.class);
        }

        // 如果缓存中不存在数据，则从数据库查询
        OperationProjectInfo projectInfo = baseMapper.selectById(projectId);

        // 将查询结果存入缓存，并设置过期时间
        if (projectInfo != null) {
            redisCacheService.setCache(cacheKey, JSON.toJSONString(projectInfo), 600);
        } else {
            // 缓存一个空值，防止缓存穿透问题
            redisCacheService.setCache(cacheKey, "null", 300); // 防止缓存穿透
        }

        return projectInfo;
    }

    public boolean updateById(OperationProjectInfo projectInfo) {
        // 更新数据库中的数据
        int i = baseMapper.updateById(projectInfo);

        // 删除缓存
        String cacheKey = CACHE_PREFIX + projectInfo.getProjectId();
        redisCacheService.deleteCache(cacheKey);

        return i > 0;
    }

}
